package com.ucode.hrm.controller.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ucode.admin.base.core.CurrentLoginUserService;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.hrm.service.HrmCustomerProjectService;
import com.ucode.model.hrm.HrmCustomerProject;
import com.ucode.model.sys.user.AdminUser;
import com.ucode.ssm.user.service.AdminUserService;
import com.ucode.tool.base.UserDataPermissionResult;
import com.ucode.tool.base.context.DataPermissionContextHolder;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.CollectionUtils;
import com.ucode.tool.util.JsonUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 数据权限辅助Service
 * @Author: Administrator
 * @Date: 2025/6/24 14:22
 * @Version: 1.0
 */
@Service
public class ApiHrmDataPermissionService {

    private static final Log log = LogFactory.get();

    @Resource
    private HrmCustomerProjectService customerProjectService;
    @Resource
    private HrmCustomerCompanyService customerCompanyService;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private CurrentLoginUserService currentLoginUserService;

    /**
     * 根据部门查询用户
     * @param deptIds
     * @return
     */
    public Set<Long> getAdminUserIdsByDeptIds(Set<Long> deptIds){
        Map<String, Object> condition = new HashMap<>();
        condition.put("deptIds",deptIds);
        condition.put("deltag",false);
        List<AdminUser> list = adminUserService.queryObjectForList(condition,0);
        return CollectionUtils.convertSet(list, AdminUser::getId);
    }

    /**
     * 获取当前用户数据权限
     * @return 可以访问的数据归属用户ID
     */
    public Set<Long> getCurrentUserByDataPermission(){
        UserDataPermissionResult userDataPermissionResult = DataPermissionContextHolder.get();

        log.info("当前用户数据权限：{}", JsonUtils.toJsonString(userDataPermissionResult));

        if(userDataPermissionResult.getAll()){
            return null;
        }

        Set<Long> userIds = new HashSet<>();
        if(CollUtil.isNotEmpty(userDataPermissionResult.getDeptIds())){
            userIds.addAll(getAdminUserIdsByDeptIds(userDataPermissionResult.getDeptIds()));
        }

        if(CollUtil.isNotEmpty(userDataPermissionResult.getUserIds())){
            userIds.addAll(userDataPermissionResult.getUserIds());
        }

        if(userIds.size() == 0){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED.getCode(),"缺少数据权限");
        }
        return userIds;
    }

    /**
     * 获取当前用户数据权限下的项目ID
     * @return 返回的项目ID如果为空则则代表可以查看所有项目，不为空则代表只能查看指定项目（注意：如果范围的空数组，代表没有可以查看的数据，业务端可以控制直接返回）
     */
    public Set<Long> getCurrentUserCustomerProjectIdsByDataPermission(){

        Set<Long> dataUserIds = getCurrentUserByDataPermission();
        if(CollUtil.isEmpty(dataUserIds))
            return null;

        Map<String,Object> condition = new HashMap<>();
        condition.put("dataUserIds",getCurrentUserByDataPermission());
        condition.put("deltag",false);

        List<HrmCustomerProject> customerProjects = customerProjectService.queryObjectForList(condition,0);

        return CollectionUtils.convertSet(customerProjects, HrmCustomerProject::getId);
    }

}
